package com.anbinh.doctor.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsMessage;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.anbinh.doctor.R;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.IRcallBak;
import com.anbinh.doctor.utils.Utils;

public class FragmentActiveAccount extends Fragment {

	private View mView;
	private static FragmentActiveAccount fragment = null;
	private IRcallBak callIResult;
	private int mType;

	private EditText edCode;
	private EditText edPhoneActive;

	private ProgressBar mLoadding;

	private TextView lblDangnhap;
	public BroadcastReceiver mybroadcast = new TextMessageReceiver();
	private String mPhone = "";

	public static FragmentActiveAccount newInstance(Bundle data) {
		if (fragment == null)
			fragment = new FragmentActiveAccount();
		fragment.setArguments(data);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof IRcallBak) {
			callIResult = (IRcallBak) activity;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.frangment_active, null);

		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		Utils.setOnTouchHideKeyboard(getActivity(), (ViewGroup) mView);

		edCode = (EditText) mView.findViewById(R.id.edCode);
		edPhoneActive = (EditText) mView.findViewById(R.id.edPhoneActive);

		mLoadding = (ProgressBar) mView.findViewById(R.id.loadding);
		lblDangnhap = (TextView) mView.findViewById(R.id.lblDangnhap);
		if (getArguments() != null) {
			mType = getArguments().getInt(Utils.KEY);
			mPhone = getArguments().getString(Utils.PHONE);
		}
		if (mPhone.isEmpty()) {
			edPhoneActive.setVisibility(View.VISIBLE);
		}
		// Demo dang ky
		Button lblNhanlaima = (Button) mView.findViewById(R.id.lblNhanlaima);
		lblNhanlaima.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mPhone.isEmpty()) {

					edPhoneActive.setVisibility(View.VISIBLE);
					mPhone = edPhoneActive.getText().toString();
					if (mPhone.isEmpty()) {
						Utils.showMessage(
								getActivity(),
								getResources().getString(
										R.string.vui_long_nhap_so_dt_nhan_ma));
						return;
					}

					if (mPhone.length() < 10 || mPhone.length() > 11) {
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.so_dien_thoai_ko_hop_le));
						return;
					}

				}

				mLoadding.setVisibility(View.VISIBLE);
				Utils.disableEnableControls(false, mView);
				ServerController.getInstance(getActivity())
						.requestdoResendActiveCode(mPhone,
								new OnRequest<DataResponse>() {

									@Override
									public void onSuccess(DataResponse data) {
										mLoadding.setVisibility(View.GONE);
										Utils.disableEnableControls(true, mView);
										Utils.showMessage(
												getActivity(),
												getResources()
														.getString(
																R.string.ma_kich_hoat_dc_gui_lai));
									}

									@Override
									public void onError(int errorCode,
											String message) {
										mLoadding.setVisibility(View.GONE);
										Utils.disableEnableControls(true, mView);
									}
								});

			}
		});

		Button btnActive = (Button) mView.findViewById(R.id.btnActive);
		btnActive.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				actionActivee();
			}
		});

		lblDangnhap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getActivity().onBackPressed();
			}
		});

	}

	public void actionActivee() {

		String mCode = edCode.getText().toString().trim();
		if (mCode.isEmpty()) {
			Utils.showMessage(getActivity(),
					getResources().getString(R.string.vui_long_nhap_so_ma_kh));
			return;
		}
		mLoadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		ServerController.getInstance(getActivity()).requestActiveRegister(
				mCode, new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);

						Utils.showMessage(getActivity(), data.getDescription());

					}

					@Override
					public void onError(int errorCode, String message) {
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
					}
				});

	}

	@Override
	public void onPause() {
		getActivity().unregisterReceiver(mybroadcast);
		super.onPause();
	}

	@Override
	public void onResume() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.provider.Telephony.SMS_RECEIVED");
		getActivity().registerReceiver(mybroadcast, filter);
		super.onResume();
	}

	public class TextMessageReceiver extends BroadcastReceiver {

		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();

			Object[] messages = (Object[]) bundle.get("pdus");
			SmsMessage[] sms = new SmsMessage[messages.length];

			for (int n = 0; n < messages.length; n++) {
				sms[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
			}

			try {
				for (SmsMessage msg : sms) {

					String arrays[] = msg.getMessageBody().split(
							"Easycare. Ma kich hoat tai khoan cua ban la");
					String s = arrays[1].toString().trim();

					String code[] = s.split(" ");

					edCode.setText(code[0]);
					actionActivee();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
